package com.efivestar.idm.api.service.lock.protocol.handler;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.domain.EventDomain;
import com.efivestar.idm.api.domain.Lock2UserDomain;
import com.efivestar.idm.api.exception.ErrorParamException;
import com.efivestar.idm.api.repository.EventMapper;
import com.efivestar.idm.api.repository.Lock2UserMapper;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.dto.PowerDto;
import com.efivestar.idm.api.util.ByteUtils;
import io.netty.buffer.ByteBuf;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class DeleteUserLockProtocolHandler extends AbstractLockProtocolHandler {

    @Autowired
    private DeviceService deviceService;


    @Autowired
    private EventMapper mapper;

    @Autowired
    private Lock2UserMapper lock2UserMapper;

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId) {
        int length = buf.readableBytes();
        //跳过指令码，不读取
        buf.skipBytes(1);
//        读取电量字节
        byte powerBt = buf.readByte();
        PowerDto power = ByteUtils.getPower(powerBt);
//        读取删除用户类型字节
        byte deleteUsertype = buf.readByte();
        int eventType = getEventType(deleteUsertype);
        byte permissiontype = buf.readByte();
        // 读取编码
        ByteBuf codeBf = buf.readBytes(2);
        String userCode = ByteUtils.getUserCode(codeBf);
        if (StringUtils.isNotEmpty(userCode) && "0510".equals(userCode)) {// ffff时为删除所有用户
            userCode = null;
        }

        //读取imei(设备编号)
        // String lockId = String.valueOf(buf.readCharSequence(length - getDataLenthWithoutDeviceId(), Charset.forName("utf-8")));
        //删除智能锁上对应的用户
        lock2UserMapper.deleteByExample(lock2UserWhereCause(lockId, userCode));

        //设置设备的电量和更新时间
        deviceService.updatePower(lockId, power.getPowerPercent());
        //事件填充到数据库
        EventDomain event = EventDomain.builder().deviceId(lockId).eventType(Cons.DELETEUSER_EVENT_TPE).subEventType(eventType).content(getPermissionType(permissiontype)).createTime(new Date()).build();
        mapper.insert(event);

        return ByteUtils.hexToBytes("00");
    }


    /**
     * 用户条件查询.
     *
     * @param lockId
     * @param userCode
     * @return
     */
    private Example lock2UserWhereCause(String lockId, String userCode) {
        Example example = new Example(Lock2UserDomain.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(lockId)) {
            criteria.andEqualTo("lockId", lockId);
        }
//        去掉锁类型
//        criteria.andEqualTo("type", userType);
        if (StringUtils.isNotEmpty(userCode)) {
            criteria.andEqualTo("userCode", userCode);
        }
        return example;
    }


    /**
     * 获取添加用户的子事件类型.
     *
     * @param eventTypeBt
     * @return
     */
    private int getEventType(byte eventTypeBt) {
        String eventType = ByteUtils.bytes2hex(eventTypeBt);
        switch (eventType) {
            case "00":
                return Cons.DELETEUSER_FIGER_EVENT;
            case "01":
                return Cons.DELETEUSER_PASSWORD_EVENT;
            case "02":
                return Cons.DELETEUSER_CARD_EVENT;
            case "03":
                return Cons.DELETEUSER_KEY_EVENT;
            case "04":
                return Cons.DELETEUSER_REMOTE_CTL_EVENT;
        }
        throw new ErrorParamException();
    }

    /**
     * 普通用户.
     */
    private static final String COMMON_USER = "1";
    /**
     * 管理员用户.
     */
    private static final String ADMIN_USER = "2";

    /**
     * 获取添加用户的权限类型
     *
     * @param permissionTypeBt
     * @return
     */
    private String getPermissionType(byte permissionTypeBt) {
        String eventType = ByteUtils.bytes2hex(permissionTypeBt);
        switch (eventType) {
            case "00":
                return COMMON_USER;
            case "01":
                return ADMIN_USER;
        }
        throw new ErrorParamException();
    }


    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 6;
    }


    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    public String udpHead() {
        return Cons.UDP_HEAD_EF01;
    }

    @Override
    public String udpCommand() {
        return Cons.UDP_COMMAND_DELET_USER;
    }

}






